<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="hAdd('0',1)">添加权限</el-button>
        </div>
        <el-table row-key="id" border :data="list">
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template #default="{row}">
              <el-button v-if="row.type == 1" type="text" @click="hAdd(row.id,2)">添加</el-button>
              <el-button type="text" @click="hEdit(row.id)">编辑</el-button>
              <el-button type="text" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-dialog
        :visible.sync="showDialog"
        :title="isEdit? '编辑' : '添加'"
        @close="resetForm"
      >
        <!-- 表单内容 -->
        <el-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="权限名称" prop="name">
            <el-input v-model.trim="formData.name" />
          </el-form-item>
          <el-form-item label="权限标识" prop="code">
            <el-input v-model.trim="formData.code" />
          </el-form-item>
          <el-form-item label="权限描述" prop="description">
            <el-input v-model="formData.description" />
          </el-form-item>
          <el-form-item label="权限启用">
            <el-switch
              v-model="formData.enVisible"
              active-text="启用"
              active-value="1"
              inactive-text="不启用"
              inactive-value="0"
            />
          </el-form-item>
        </el-form>

        <template #footer>
          <div style="text-align: right;">
            <el-button @click="showDialog = false">取消</el-button>
            <el-button type="primary" @click="hSubmit">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { tranListToTreeList } from '@/utils'
import { addPermission, delPermission, getPermissionDetail, getPermissionList, updatePermission } from '@/api/permissions'
export default {
  data() {
    // 自定义效验
    const validCode = (rule, value, callback) => {
      // 添加时的校验：code不能重复
      let existCodeList = this.originList
      if (this.isEdit) {
        // 编辑时的校验: code能取自己
        existCodeList = this.originList.filter(item => item.id !== this.formData.id)
      }
      existCodeList.map(it => it.code).includes(value)
        ? callback(new Error(value + '已经占用'))
        : callback()
    }

    const validName = (rule, value, callback) => {
      // 添加时的校验： 名字不能取子元素的名字
      let existNameList = this.originList.filter(item => item.pid === this.formData.pid)
      if (this.isEdit) {
        // 编辑时的校验： 名字不能取兄弟（排除自己）的名字
        // 找兄弟，排除自己
        existNameList = this.originList.filter(item => item.pid === this.formData.pid && item.id !== this.formData.id)
      }
      existNameList.map(it => it.name).includes(value)
        ? callback(new Error(value + '已经占用'))
        : callback()
    }
    return {
      list: [],
      isEdit: false, // 编辑状态
      showDialog: false, // 是否显示弹层
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      originList: [], // 在做校验时需要用到的数据
      rules: {
        name: [
          { required: true, message: '权限名称', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }

        ],
        code: [
          { required: true, message: '权限标识 ', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],

        description: [
          { required: true, message: '权限描述', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.loadPermissionList()
  },
  methods: {
    // 清空表单
    resetForm() {
      // 清空数据
      this.formData = {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      }
      this.$refs.formRef.resetFields() // 清空效验规则
    },
    // 添加
    hAdd(pid, type) {
      this.formData.pid = pid
      this.formData.type = type
      this.showDialog = true
      this.isEdit = false
    },
    // 提交
    hSubmit() {
      // 兜底效验
      this.$refs.formRef.validate(valid => {
        if (!valid) return
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    // 删除权限
    hDel(id) {
      this.$confirm('你确定删除该权限吗?').then(async() => {
        try {
          await delPermission(id)
          this.loadPermissionList()
        } catch (err) {
          console.log('del', err)
        }
      }).catch((err) => console.log(err))
    },
    // 编辑
    hEdit(id) {
      this.isEdit = true
      this.showDialog = true
      this.loadPermissionDetail(id)
    },
    async doAdd() {
      try {
        const res = await addPermission(this.formData)
        console.log('addPermission', res)
        // 保存数据
        this.showDialog = false
        this.loadPermissionList()
      } catch (err) {
        console.log('addPermission', err)
      }
    },
    async loadPermissionList() {
      try {
        const res = await getPermissionList()
        console.log('获取权限数据', res)
        this.originList = res.data.map(({ id, pid, name, code }) => ({ id, pid, name: name.trim(), code }))
        this.list = tranListToTreeList(res.data)
      } catch (err) {
        console.log(err)
      }
    },
    async doEdit() {
      // 实现编辑
      try {
        const res = await updatePermission(this.formData)
        console.log('updatePermission', res)
        // 保存数据
      } catch (err) {
        console.log('updatePermission', err)
      }
    },
    // 进行数据回显
    async loadPermissionDetail(id) {
      try {
        const res = await getPermissionDetail(id)
        console.log('getPermissionDetail', res)
        this.formData = res.data
        // 保存数据
      } catch (err) {
        console.log('getPermissionDetail', err)
      }
    }
  }
}
</script>
